// BSD License (http://www.galagosearch.org/license)
package org.galagosearch.core.tools;

import java.io.IOException;
import java.io.PrintStream;
import java.util.List;
import java.util.StringTokenizer;

import org.galagosearch.core.retrieval.Retrieval;
import org.galagosearch.core.retrieval.ScoredDocument;
import org.galagosearch.core.retrieval.query.Node;
import org.galagosearch.core.retrieval.query.SimpleQuery;
import org.galagosearch.core.retrieval.query.StructuredQuery;
import org.galagosearch.tupleflow.Parameters;

/**
 *
 * @author trevor
 */
public class BatchSearch {
	static boolean isTC=false;
    public static Node parseQuery(String query, Parameters parameters) {
        String queryType = parameters.get("queryType", "complex");

        if (queryType.equals("simple")) {
            return SimpleQuery.parseTree(query);
        }

        return StructuredQuery.parse(query);
    }

    public static String formatScore(double score) {
        double difference = Math.abs(score - (int) score);

        if (difference < 0.00001) {
            return Integer.toString((int) score);
        }
        return String.format("%10.8f", score);
    }

    public static void run(String[] args, PrintStream out) throws Exception {
        // read in parameters
        Parameters parameters = new Parameters(args);
        List<Parameters.Value> queries = parameters.list("query");

        // open index
        Retrieval retrieval = Retrieval.instance(parameters.get("index"), parameters);


        // record results requested
        int requested = (int) parameters.get("count", 1000);

        // for each query, run it, get the results, look up the docnos, print in TREC format
        for (Parameters.Value query : queries) {
            // parse the query
            String queryText = query.get("text");
            String queryDate = query.get("date");
            //out.format("%s",new String("DATE"));
            Node queryRoot = parseQuery(queryText, parameters);
            queryRoot = retrieval.transformQuery(queryRoot);
            
            retrieval.ipTime = queryDate;
            ScoredDocument[] results;
            if(isTC) results = retrieval.runQueryTC(queryRoot, requested);
            else results = retrieval.runQuery(queryRoot, requested);
            
            for (int i = 0; i < results.length; i++) {
            	 String identifier = retrieval.getDocumentName(results[i].document);
                 int tempPos=identifier.lastIndexOf('+');
                 int revID=Integer.parseInt(identifier.substring(tempPos+1));
                 identifier=identifier.substring(0, tempPos);
                 tempPos=identifier.lastIndexOf('+');
                 String timeEnd=identifier.substring(tempPos+1);
                 identifier=identifier.substring(0, tempPos);
                 tempPos=identifier.lastIndexOf('+');
                 String timeBegin=identifier.substring(tempPos+1);
                 identifier=identifier.substring(0,tempPos);
                 
                 if( isTC || checkDocumentValidity(queryDate,timeBegin,timeEnd))
                 {
	            //	String document = retrieval.getDocumentName(results[i].document);
                	 if(isTC==true){
     	            	//String strTimeBegin = results[i].timeB.toString();
     	            	//String strTimeBegin = results[i].timeB.toString();
     	            	//item.metadata.put("timeBegin",intTimeToStringTime(results[i].timeB));
     	            	//item.metadata.put("timeEnd",intTimeToStringTime(results[i].timeE));
     	            	timeBegin=Integer.toString(results[i].timeB);
     	            	timeEnd=Integer.toString(results[i].timeE);
     	            }
                	 String document=identifier+"@["+timeBegin+","+timeEnd+"]";
                	 double score = results[i].score;
                	 int rank = i + 1;
                	 out.format("%s Q0 %s %d %s %s galago\n", query.get("number"), document, rank,
	                           formatScore(score), queryDate);
                 }
            }
        }
    }

    public static void main(String[] args) throws Exception {
        run(args, System.out);
    }
    public static boolean checkDocumentValidity(String inputTime, String timeBegin, String timeEnd){

		boolean isValid = false;
		
		//int inpTime = stringTimetoIntTime(inputTime);
		int inpTime = stringInputTImetoIntInputTime(inputTime);
		int timeB = stringTimetoIntTime(timeBegin);
		if(timeEnd.trim().compareTo("-1")==0){
			//int timeE = -1;
			if(timeB<=inpTime)
				isValid = true;
		}
		else{
			int timeE = stringTimetoIntTime(timeEnd);
			if(timeB<=inpTime && timeE>=inpTime)
				isValid = true;
		}	
		return isValid;
	}
    private static int stringInputTImetoIntInputTime(String inputTime) {
		// TODO Auto-generated method stub
		StringTokenizer str = new StringTokenizer(inputTime,"-");
		//System.out.println(inputTime);
		String s1=(String) str.nextElement();
		String s2=(String) str.nextElement();
		String s3=(String) str.nextElement();
		
		if(s2.length()==1)
			s2 = "0"+s2;
		
		String outputString = s3.substring(2, 4) + s2 + s1 + "0000";
	//	System.out.println("year = "+s3.substring(2, 4)+"month = "+s2+"Date: "+s1+"Output: "+outputString);
		return Integer.parseInt(outputString);
	}
	public static int stringTimetoIntTime(String timeStamp){

//		System.out.println("timeStamp:"+timeStamp);
		String substr=timeStamp.substring(2,4);
		String s1=timeStamp.substring(5,7);
		String s2=timeStamp.substring(8,10);
		String s3=timeStamp.substring(11,13);
		String s4=timeStamp.substring(14,16);
		String str= substr + s1  + s2 + s3 + s4;
		int i=Integer.parseInt(str);
		return i;
	}
}
